﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace CDoDNSessionScheduler
{
    public partial class Page : UserControl
    {
        private bool ChecklistCaptured;
        private double MousePositionX;
        private double MousePositionY;
        private bool PrintFriendlyState;
        private double ChecklistMultiplier;

        public Page()
        {
            InitializeComponent();

            CheckList.SizeChanged += new SizeChangedEventHandler(CheckList_SizeChanged);
            ChecklistGrow.Completed += new EventHandler(ChecklistGrow_Completed);
            ChecklistCaptured = false;
            PrintFriendlyState = false;
            ChecklistMultiplier = 0.0;

            GlobalVariables.Get().RootGrid = LayoutRoot;
            GlobalVariables.Get().MainChecklist = CheckList;
            GlobalVariables.Get().MainSessionList = SessionGrid;

            XDocument sessionList = new XDocument();
            sessionList = XDocument.Load("LocalResources/SessionList.xml");
            
            List<ScheduleTrack> FullTracks = new List<ScheduleTrack>();
            IEnumerable<XElement> tracks = sessionList.Descendants("track");
            foreach (XElement track in tracks)
            {
                ScheduleTrack activeTrack = new ScheduleTrack();
                activeTrack.Id = Convert.ToInt32(track.Attribute("id").Value);
                activeTrack.Name = (string)track.Element("name").Value;
                activeTrack.BackColor = (string)track.Element("color").Value;
                FullTracks.Add(activeTrack);

                RowDefinition rd = new RowDefinition();
                rd.Height = new GridLength(75);
                SessionGrid.RowDefinitions.Add(rd);
            }

            List<ScheduleTimeSlot> FullTimeslots = new List<ScheduleTimeSlot>();
            IEnumerable<XElement> slots = sessionList.Descendants("slot");
            int columnNumber = 0;
            int TextPadPlacement = 5;
            foreach (XElement slot in slots)
            {
                ScheduleTimeSlot ts = new ScheduleTimeSlot();
                ts.Id = Convert.ToInt32(slot.Attribute("id").Value);
                ts.StartTime = Convert.ToDateTime(slot.Element("start").Value);
                ts.EndTime = Convert.ToDateTime(slot.Element("end").Value);
                ts.SlotType = (string)slot.Attribute("type").Value;
                FullTimeslots.Add(ts);
                
                //Add Column to session grid
                ColumnDefinition cd = new ColumnDefinition();
                if (ts.SlotType == "admin") cd.Width = new GridLength(40);
                else cd.Width = new GridLength(75);
                SessionGrid.ColumnDefinitions.Add(cd);

                //Add row to individual schedule
                ScheduledItem item = new ScheduledItem();
                item.SessionName.Text = "";
                item.StartTime.Text = ts.StartTime.ToShortTimeString() + " - " + ts.EndTime.ToShortTimeString();
                if (ts.SlotType == "admin") item.SessionName.Text = (string)slot.Attribute("admintext").Value;
                CheckList.Children.Add(item);


                TextBlock tb = new TextBlock();
                tb.Text = ts.StartTime.ToShortTimeString() + " - " + ts.EndTime.ToShortTimeString();
                tb.FontSize = 9;
                tb.VerticalAlignment = VerticalAlignment.Center;
                tb.HorizontalAlignment = HorizontalAlignment.Center;
                tb.FontFamily = new FontFamily("Verdana");
                tb.MaxWidth = 65;
                //tb.MaxHeight = 35;
                tb.TextWrapping = TextWrapping.Wrap;
                SessionGrid.Children.Add(tb);
                Grid.SetColumn(tb, columnNumber);
                Grid.SetRow(tb, 0);

                if (ts.SlotType == "admin")
                {
                    AdminSession re = new AdminSession();
                    re.BackHeight = FullTracks.Count * 75;
                    re.AdminTitle.Text = (string)slot.Attribute("admintext").Value;
                    SessionGrid.Children.Add(re);
                    Grid.SetColumn(re, columnNumber);
                    Grid.SetRow(re, 1);
                    Grid.SetRowSpan(re, FullTracks.Count);
                }

                columnNumber++;
                TextPadPlacement += (int)cd.Width.Value;
            }

            ChecklistHolder.SetValue(Canvas.LeftProperty, TextPadPlacement);
            

            IEnumerable<XElement> rawSessions = sessionList.Descendants("session");
            foreach (XElement session in rawSessions)
            {

                Session activeSession = new Session();
                activeSession.Author = (string)session.Element("presenter").Value;
                activeSession.Title = (string)session.Element("title").Value;
                foreach (ScheduleTrack tr in FullTracks)
                {
                    if (tr.Id == (int)session.Attribute("track"))
                    {
                        activeSession.Track = tr;
                        break;
                    }
                }
                activeSession.Description = (string)session.Element("synopsis").Value;
                activeSession.Bio = (string)session.Element("presenterbio").Value;
                activeSession.TimeSlot = (int)session.Attribute("slot");

                SessionGrid.Children.Add(activeSession);
                Grid.SetColumn(activeSession, (int)session.Attribute("slot"));
                Grid.SetRow(activeSession, activeSession.Track.Id);

                // check whether this session has been scheduled by the user, and select it if so
                if (GlobalVariables.Get().UserSchedule.Tracks[activeSession.TimeSlot - 1] == activeSession.Track.Id)
                    activeSession.Selected = true;
            }
        }

        void ChecklistGrow_Completed(object sender, EventArgs e)
        {
            ChecklistCaptured = false;
            MousePositionX = -1;
            MousePositionY = -1;
        }

        void CheckList_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            CheckListBack.Height = CheckList.ActualHeight + 25;
        }

        #region Checklist Drag Drop handlers
        private void CheckList_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ChecklistCaptured = true;
            MousePositionX = e.GetPosition(null).X;
            MousePositionY = e.GetPosition(null).Y;
        }

        private void CheckList_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ChecklistCaptured = false;
            MousePositionX = -1;
            MousePositionY = -1;
        }

        private void CheckList_MouseMove(object sender, MouseEventArgs e)
        {
            if (ChecklistCaptured)
            {
                double deltaY = e.GetPosition(null).Y - MousePositionY;
                double deltaX = e.GetPosition(null).X - MousePositionX;

                double newTop = deltaY + (double)Canvas.GetTop(ChecklistHolder);
                double newLeft = deltaX + (double)Canvas.GetLeft(ChecklistHolder);

                Canvas.SetTop(ChecklistHolder, newTop);
                Canvas.SetLeft(ChecklistHolder, newLeft);

                MousePositionY = e.GetPosition(null).Y;
                MousePositionX = e.GetPosition(null).X;
            }
        }
        #endregion

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!PrintFriendlyState)
            {
                ChecklistMultiplier = (this.ActualHeight - 47) / CheckList.ActualHeight;
                ChecklistGrowScaleX.KeyFrames[0].Value = 1;
                ChecklistGrowScaleY.KeyFrames[0].Value = 1;
                ChecklistChangeLeft.KeyFrames[0].Value = (double)Canvas.GetLeft(ChecklistHolder);
                ChecklistGrowScaleX.KeyFrames[1].Value = ChecklistMultiplier;
                ChecklistGrowScaleY.KeyFrames[1].Value = ChecklistMultiplier;
                ChecklistChangeLeft.KeyFrames[1].Value = 200;

                ChecklistGrow.Begin();
                Canvas.SetZIndex(ChecklistHolder, 100);
                PrintFriendlyState = true;

                ImageAdd.Visibility = Visibility.Collapsed;
                ImageUndo.Visibility = Visibility.Visible;
            }
            else
            {
                ChecklistGrowScaleX.KeyFrames[0].Value = ChecklistMultiplier;
                ChecklistGrowScaleY.KeyFrames[0].Value = ChecklistMultiplier;
                ChecklistChangeLeft.KeyFrames[0].Value = (double)Canvas.GetLeft(ChecklistHolder);
                ChecklistGrowScaleX.KeyFrames[1].Value = 1;
                ChecklistGrowScaleY.KeyFrames[1].Value = 1;
                ChecklistChangeLeft.KeyFrames[1].Value = 649;

                ChecklistGrow.Begin();
                Canvas.SetZIndex(ChecklistHolder, 0);
                PrintFriendlyState = false;

                ImageAdd.Visibility = Visibility.Visible;
                ImageUndo.Visibility = Visibility.Collapsed;
            }
        }
    }

    public class ScheduleTrack
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string BackColor { get; set; }
    }

    public class ScheduleTimeSlot
    {
        public int Id { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public string SlotType { get; set; }
    }
}
